<?php

namespace App\Modules\Blog\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\QueryBuilder\QueryBuilder;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\AllowedInclude;
use App\Modules\Blog\Models\Post;
use App\Modules\Blog\Models\Cate;
use App\Modules\Blog\Http\Resources\PostResource;
use App\Modules\Blog\Http\Requests\PostCreateRequest;
use App\Modules\Blog\Http\Requests\PostUpdateRequest;
use App\Http\Controllers\Controller;

class PostController extends Controller
{

    protected $model;
    protected $request;
    /**
     * current Module
     */
    protected $module = "blog";
    protected $modelclass = Post::class;

    /**
     * Display a listing of the resource.
     * 查询
     * ?filter[cate_id]=10&title=imya
     * ?field['posts']=id,user_id,cate_id,title&field['user']=id,name&field[cate]=id,title
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $model = new Post();
        $initSet = $model->getInitSet();
        dump($request->include);
        $request->merge($initSet);
        $listSet = $model->getInitList();

        dump($request->include);
        $data = QueryBuilder::for($model->fastQuery(),$request)
                ->defaultSort( $listSet['sort'] ?? '-created_at')
                ->allowedSorts($listSet['sorts'] ?? '')
                ->allowedFields($listSet['fields'] ?? '')
                ->allowedFilters($listSet['filters'] ?? '')
                ->allowedAppends($listSet['appends'] ?? '')
                ->allowedIncludes($listSet['includes'] ?? '')
                ->paginate(10);

        return json_ok($data->toArray());    
        $page = $request->get('page',1);
        $per_page = $request->get('per_page',10);
        $limit = $request->get('limit',0);

        $qset = $model->getQuerySet();

        $data = QueryBuilder::for($model->filters())
            ->defaultSort($qset['sort']??'-created_at')
            ->allowedSorts($qset['sorts'])
            ->allowedFields($qset['fields'])
            ->allowedFilters($qset['filters'])
            ->allowedIncludes($qset['includes'])
            ->allowedAppends($qset['appends']);
        if($limit){
            $data = $data->simplePaginate($limit);
        }else{
            $data = $data->paginate($per_page);
        }

        $data = $data->appends($request->query());
        return json_ok($data->toArray());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Modules\Blog\Http\Requests\BlogCreateRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(BlogCreateRequest $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Post::with(Post::showWith())->findOrFail($id);
        $result['data'] = (new PostResource($data))->resolve();
        $result['module'] = get_module($this->module);
        dd($result);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Modules\Blog\Http\Requests\BlogUpdateRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(BlogUpdateRequest $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    protected function queryBuilder($query,array $param=[])
    {       
//sql_start();
        $request=request();
        if(!$request->has('include') && !empty($param['list_with'])){
            //list_with必须在includes范围内,否则会出错
            $request->offsetSet('include', str2arr($param['list_with']));
        }
            //dump("defaultIncludes('".arr2str($param['includes'])."')");
        $data = QueryBuilder::for($query);
        
        if($param['sort']){
            $data = $data->defaultSort($param['sort']);
            //dump("defaultSort('".$param['sort'].")");
        }                 
        if($param['sorts']){
            $data = $data->allowedSorts($param['sorts']);
            //dump("allowedSorts('".arr2str($param['sorts'])."')");
        }
        if($param['filters']){
            $data = $data->allowedFilters($param['filters']);
            //dump("allowedFilters('........')");
        }
        if($param['fields']){
            $data = $data->allowedFields($param['fields']);
            //dump($request->get('fields'));
        }
        if($param['appends']){     
            $data = $data->allowedAppends($param['appends']);
            //dump("defaultAppends('".arr2str($param['appends'])."')");
        }
        if($param['includes']){
            $data = $data->allowedIncludes($param['includes']);
        }
        
		$limit    = (int)$request->get('limit',0);
        $per_page = (int)$request->get('per_page',0);

        if( $limit > 0 ){
            $data = $data->simplePaginate($limit);
        }elseif($per_page > 0){
            $data = $data->paginate($per_page);
        }else{
            $data = $data->paginate();   
        }        
        $data = $data->appends($request->query());
        return $data;

//sql_end();           
    }  

    protected function help(Request $request)
    {
		$query	= [
			'include' => config('query-builder.parameters.include'),
			'filter'  => config('query-builder.parameters.filter'),
			'sort'    => config('query-builder.parameters.sort'),
			'fields'  => config('query-builder.parameters.fields'),
			'append'  => config('query-builder.parameters.append')
			];
		$allowed = [
			'include' => Post::allowedIncludes(),
			'filter'  => Post::allowedFilters(),
			'sort'    => Post::allowedSorts(),
			'fields'  => Post::allowedFields(),
			'append'  => Post::allowedAppends()
			];
		$default = [
			'with'   => Post::listWith(),
			'fields' => Post::listFields(),
			'sort'   => '-created_at',
            ];
            
        
        foreach ($allowed['filter'] as $key => $value) {
            if($value instanceof AllowedFilter){
                $allowed['filter'][$value->getName()] = $value->getInternalName(); 
            }else{
                $allowed['filter'][$value]='like';
            }
            unset($allowed['filter'][$key]);
        }
        $simple = 'limit';
        return json_ok(compact('query','allowed','default','simple'));
    }    

    public function Test()
    {
        $includes = request('include');
        if(!empty($includes)){            
            $includes = ($includes === 'null') ? false : str2arr($includes);
        }
dd($includes);
$a2=['b','d','e','f'];
dd(array_intersect_key($a1,array_flip($a2)));
$result=array_diff_key($a1,$a2);
print_r($result);
    }
}
